package cn.zhaoyuening.hnistalumnirecord.web.controller;

import cn.zhaoyuening.hnistalumnirecord.domain.ConfigItem;
import cn.zhaoyuening.hnistalumnirecord.domain.News;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.Serializable;
import java.util.List;

/**
 * Created by zhao on 17-1-17.
 */
@Controller
@RequestMapping("/news")
public class NewsController extends BaseController{
    private static Gson skipModuleAndContentGson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes fieldAttributes) {
            return fieldAttributes.getName().equals("module")||fieldAttributes.getName().equals("content");
        }

        @Override
        public boolean shouldSkipClass(Class<?> aClass) {
            return false;
        }
    }).create();

    @RequestMapping(value = "getNewsJsonData.do",produces = "application/json; charset=utf-8")
    @ResponseBody
    //分页方式返回news的json数据集合
    public String getNewsJsonData(@RequestParam("moduleId")Serializable moduleId, @RequestParam("pageNumber")int pageNumber, @RequestParam("pageSize") int pageSize) {

        List<News> newsList = getNewsService().findByModuleId(moduleId,pageNumber,pageSize);
        String json = skipModuleAndContentGson.toJson(newsList);
        //总数
        long total = getNewsService().getTotalRecordByModuleId(moduleId);
        return "{\"total\":"+total+",\"data\":"+json+"}";
    }

    @RequestMapping("read.do")
    public String readNews(@RequestParam("id")int id,Model model){
        News news = getNewsService().findById(id);
        ConfigItem configItem = getConfigItemService().findById(1);
        model.addAttribute("news", news);
        model.addAttribute("configItem", configItem);
        return "newsView";
    }

    /**
     * 通过索引搜索news
     * @param searchContent
     * @param model
     * @return
     */
    @RequestMapping("search.do")
    public String search(@RequestParam("searchContent")String searchContent,Model model){
        List<News> newsList = getNewsService().search(searchContent);
        model.addAttribute("newsList", newsList);
        return "searchResult";
    }



}
